package com.open.capacity.reimburse.dto;

import com.open.capacity.reimburse.entity.SysInvoice;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;

public class DuplicateInvoiceFilter {
    private DuplicateInvoiceFilter() {
        //No instances of this class
    }

    public static List<SysInvoice> getDuplicates(final List<SysInvoice> personList) {

        return personList
                .stream()
                .filter(duplicateByKey(SysInvoice::getNumber))
                .collect(Collectors.toList());

    }

    private static <T> Predicate<T> duplicateByKey(final Function<? super T, Object> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> !isNull(seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE));

    }
}
